package com.zzyl.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.properties.WeChatMiniProgramProperties;
import com.zzyl.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WechatServiceImpl implements WechatService {


    @Autowired
    private WeChatMiniProgramProperties properties;
    private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    @Override
    public String getOpenid(String code) {


        Map<String, Object> paramMap = new HashMap<>();

        paramMap.put("appid",properties.getAppid());
        paramMap.put("secret",properties.getAppSecret());
        paramMap.put("js_code",code);
        paramMap.put("grant_type","client_credential");
        String result = HttpUtil.get(OPENID_URL, paramMap);

        JSONObject jsonObject = JSONUtil.parseObj(result);
        // 若code不正确[即errcode存在]，则获取不到openid，响应失败【errmsg】
        Integer errcode = jsonObject.getInt("errcode");
        if (ObjectUtil.isNotEmpty(errcode)){ // 有问题响应失败
            log.error("获取openid失败：错误码：{},错误信息：{}",
                    errcode,
                    jsonObject.getStr("errmsg"));
            throw new RuntimeException(jsonObject.getStr("errmsg"));

        }

        return jsonObject.getStr("openid");
    }

    @Override
    public String getPhone(String code) {

        // 获取access_token
        String accessToken = getAccessToken();
        Map<String,String> codeMap = new HashMap<>();
        codeMap.put("code",code);
        String result = HttpUtil.post(PHONE_URL+accessToken,
                JSONUtil.toJsonStr(codeMap));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        Integer errcode = jsonObject.getInt("errcode");
        if (errcode != 0){
            log.error("获取手机号失败：错误码：{},错误信息：{}",
                    errcode,
                    jsonObject.getStr("errmsg"));
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }


        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }

    /**
     * 获取令牌
     * @return
     */
    private String getAccessToken(){
        Map<String, Object> paramMap = new HashMap<>();

        paramMap.put("appid",properties.getAppid());
        paramMap.put("secret",properties.getAppSecret());
        paramMap.put("grant_type","client_credential");
        String result = HttpUtil.get(ACCESS_TOKEN_URL, paramMap);

        JSONObject jsonObject = JSONUtil.parseObj(result);
        return jsonObject.getStr("access_token");
    }
}
